//
//  RegisterViewController.m
//  XPhoto
//
//  Created by baboy on 2019/7/26.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "RegisterViewController.h"
#import "User.h"
#import "BKIndicator.h"
#import "NSString+x.h"
#import "UIViewController+x.h"
#import "VerificationCodeViewController.h"
#import "ProfileEditViewController.h"
#import "ProfileEditViewController.h"
#import <BKKit/BKNavigationController.h>

@interface RegisterViewController ()<VerificationCodeDelegate, ProfileEditDelegate>

@end

@implementation RegisterViewController
- (id)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]){
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationController.navigationBar.hidden = YES;
    // Do any additional setup after loading the view from its nib.
}
- (NSArray*)checkConfig{
    return @[
             @{
                 @"field":self.mobileTextField,
                 @"name":NSLocalizedString(@"mobile_no", @"标签"),
                 @"min-len":@11,
                 @"max-len":@11,
                 @"regex":@"1[3-9]{1}\\d{9}"
                 }
             ];
}
- (IBAction)nextStep:(nullable id)button{
    BOOL ret = checkInput([self checkConfig], ^(NSString *errorMsg) {
        [BKIndicator showMessageAndFadeOut:errorMsg completion:nil];
    });
    if (!ret) {
        return;
    }
    NSString *mobile = [self.mobileTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    [self sendSmsCode:mobile callback:^(id  _Nullable response, NSError * _Nullable error) {
        if (error) {
            return;
        }
        VerificationCodeViewController *vc = [[VerificationCodeViewController alloc] init];
        vc.mobile = mobile;
        vc.delegate = self;
        [self.navigationController pushViewController:vc animated:YES];
    }];
}
- (void)sendSmsCode:(NSString *)mobile callback:(nullable void (^)( id _Nullable response,  NSError * _Nullable error))callback{
    [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"sending", @"提示") completion:nil];
    [User sendRegisterMobileVCode:mobile
                     callback:^(id  _Nonnull task, id  _Nullable response, NSError * _Nullable error) {
        if (error) {
            DLOG(@"%@", error.localizedDescription)
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
        }
        if(!error){
            [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"vcode_send_success", @"提示") completion:nil];
        }
        if (callback) {
            callback(response, error);
        }
    }];
}
- (void)registerWithMobile:(NSString *)mobile vcode:(NSString *)vcode{
    UserRegisterMobileArgs *args = [UserRegisterMobileArgs new];
    args.mobile = mobile;
    args.vcode = vcode;
    [BKIndicator showMessage:NSLocalizedString(@"registering", @"描述")];
    [User signupWithMobile:args
                  callback:^(id  _Nonnull task, id  _Nullable user, NSError * _Nullable error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
            return;
        }
        [BKIndicator showMessage:NSLocalizedString(@"register_success", @"描述")];
        [User login:user];
        [self.navigationController dismissViewControllerAnimated:YES completion:^{
            ProfileEditViewController *vc = [[ProfileEditViewController alloc] init];
            BKNavigationController *nav = [[BKNavigationController alloc] initWithRootViewController:vc];
            nav.modalPresentationStyle = UIModalPresentationFullScreen;
            [self.navigationController presentViewController:nav animated:YES completion:nil];
        }];
    }];
}
#pragma mark - VerificationCodeDelegate
- (void)verificationCodeViewControllerWillResendVCode:(VerificationCodeViewController *)vc{
    [self sendSmsCode:vc.mobile callback:nil];
}
- (void)verificationCodeViewController:(VerificationCodeViewController *)vc didInputVCode:(NSString *)vcode{
    [self registerWithMobile:vc.mobile vcode:vcode];
}
#pragma mark - ProfileEditDelegate
- (BOOL)profileEditViewControllerShouldCancel:(ProfileEditViewController *)vc{
    [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"complete_profile_desc", @"提示") completion:nil];
    return NO;
}
- (BOOL)profileEditViewControllerShouldFinished:(ProfileEditViewController *)vc{
    NSString *userName = [vc.updatedUserInfo valueForKey:@"userName"];
    if (!userName) {
        userName = [[User currentUser] userName];
    }
    NSString *nickname = [vc.updatedUserInfo valueForKey:@"nickname"];
    if (!nickname) {
        nickname = [[User currentUser] nickname];
    }
    
    if (!userName || !nickname) {
        [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"userName_or_nickname_not_null_desc", @"提示") completion:nil];
        return NO;
    }
    if (vc.updatedUserInfo) {
        User *user = [User currentUser];
        for (NSString *k in vc.updatedUserInfo.allValues) {
            id v = [vc.updatedUserInfo valueForKey:k];
            [user setValue:v forKey:k];
        }
        [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"submitting", @"提交数据") completion:nil];
        [User update:user
            callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
            if (error) {
                [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
                return;
            }
            [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"submit_now", @"提交数据") completion:nil];
            [vc dismissViewControllerAnimated:YES completion:nil];
        }];
        return NO;
    }
    
    return NO;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
